package com.allenyuan.render;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

import com.allenyuan.renderobject.RenderObject;
import com.allenyuan.renderobject.RenderPoint;
import com.allenyuan.renderobject.RenderTransformRectangle;

public class RenderObjectPool {
	
	private static RenderObjectPool instance;
	
	public static RenderObjectPool getInstance() {
		if (instance == null) {
			instance = new RenderObjectPool();
		}
		return instance;
	}
	
	private List<RenderObjectList> renderObjectLists;
	
	public static final int RENDER_LIST_DATA = 0;
	public static final int RENDER_LIST_TRANSFORM = 1;
	public static final int RENDER_LIST_MAX = 2;

	private RenderObjectPool() {
		renderObjectLists = new ArrayList<RenderObjectList>(RENDER_LIST_DATA);
		for (int i = 0; i < RENDER_LIST_MAX; ++i) {
			renderObjectLists.add(new RenderObjectList());
		}
	}
	
	public void addRenderObject(RenderObject obj, int listNo) {
		renderObjectLists.get(listNo).add(obj);
	}
	
	public void render(Renderer r) {
		Iterator<RenderObjectList> it = renderObjectLists.iterator();
		while (it.hasNext()) {
			it.next().render(r);
		}
	}
	
	public RenderObject getLast(int listNo) {
		return renderObjectLists.get(listNo).getLast();
	}
	
	public RenderObject getLastContainPoint(RenderPoint point) {
		RenderObjectList renderObjects = renderObjectLists.get(RENDER_LIST_DATA);
		ListIterator<RenderObject> it = renderObjects.listIterator(renderObjects.size());
		RenderObject renderObject = null;
		while (it.hasPrevious()) {
			renderObject = it.previous();
			if (renderObject.contains(point)) {
				return renderObject;
			}
		}
		return null;
	}

	
	public void setNoSelect() {
		RenderObjectList renderObjects = renderObjectLists.get(RENDER_LIST_TRANSFORM);
		ListIterator<RenderObject> it = renderObjects.listIterator();
		while (it.hasNext()) {
			RenderObject obj = it.next();
			((RenderTransformRectangle)obj).getObj().setSelected(false);
			it.remove();
		}
		renderObjects.clear();
	}
	
	public void moveSelectedObject(int x, int y) {
		RenderObjectList renderObjects = renderObjectLists.get(RENDER_LIST_TRANSFORM);
		Iterator<RenderObject> it = renderObjects.iterator();
		while (it.hasNext()) {
			RenderTransformRectangle rectangle = (RenderTransformRectangle)it.next();
			rectangle.move(x, y);
			rectangle.getObj().move(x, y);
		}
	}
	
	public void drawProgressLastObect(int mouse, RenderPoint point) {
		RenderObject renderObject = renderObjectLists.get(RENDER_LIST_DATA).getLast();
		renderObject.drawProgress(mouse, point);
	}
}
